package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.DishDto;
import com.example.mapper.DishMapper;
import com.example.pojo.Dish;
import com.example.pojo.DishFlavor;
import com.example.service.DishFlavorService;
import com.example.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存口味数据到口味表
     * @param dishDto
     */
    @Override
    @Transactional  //涉及多张表，要保证事务一致性
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息到dish表
        this.save(dishDto);

        //此时MP返回了主键id，可以直接拿到
        Long dishId = dishDto.getId();

        //为DishFlavor对象赋上dishId
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor: flavors) {
            flavor.setDishId(dishId);
        }


        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 查出菜品信息和对应口味
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //根据Id查出菜品，但此时没有口味信息
        Dish dish = this.getById(id);
        //构建有口味信息的DishDto对象
        DishDto dishDto = new DishDto();
        //将查出来的dish对象属性拷贝到dishDto中
        BeanUtils.copyProperties(dish, dishDto);

        //从口味表中根据dishId查出菜品对应口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

        //将查出的口味列表赋给dishDto的对应属性
        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    /**
     * 更新菜品信息，同时更新口味表
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新菜品基本信息
        this.updateById(dishDto);

        //删除原先的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //为DishFlavor对象赋上dishId
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor: flavors) {
            flavor.setDishId(dishDto.getId());
        }

        //插入当前提交的口味信息
        dishFlavorService.saveBatch(flavors);
    }
}
